package com.grad.webstudy.context;

import com.grad.webstudy.enums.ExceptionEnums;
import com.grad.webstudy.exceptions.CustomException;
import com.grad.webstudy.model.User;

import java.util.Objects;

/**
 * @Description: 主要用于获取当前登录用户
 * @Author: zjf
 * @Date: 2020/1/21 17:42.
 */
public class UserContext {

    private static ThreadLocal<User> userThreadLocal =new ThreadLocal<User>();

    public static void setLoginUser(User user){
        userThreadLocal.set(user);
    }

    public static User getLoginUser(){
        User user = userThreadLocal.get();
        if (Objects.isNull(user)){
            //获取的用户为空，抛出未登录异常
            throw new CustomException(ExceptionEnums.TOKEN_INVALID.getCode(),
                    ExceptionEnums.TOKEN_INVALID.getMessage());
        }
        return user;
    }

    public static void removeLoginUser(){
        userThreadLocal.remove();
    }
}
